package com.socialsoftware.ui.Messages;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.socialsoftware.Page.ChatDetailActivity;
import com.socialsoftware.R;
import com.socialsoftware.adapter.MessageAdapter;
import com.socialsoftware.model.Message;

import java.util.ArrayList;
import java.util.List;

public class MessageListFragment extends Fragment {

    private RecyclerView recyclerView;
    private MessageAdapter adapter;
    private ProgressBar progressBar;
    private TextView tvEmptyState;
    private List<Message> messageList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_message_list, container, false);
        
        // Initialize views
        recyclerView = root.findViewById(R.id.recyclerView);
        progressBar = root.findViewById(R.id.progressBar);
        tvEmptyState = root.findViewById(R.id.tvEmptyState);
        
        // Set up RecyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        
        // Add item decoration for dividers
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(
                recyclerView.getContext(), layoutManager.getOrientation());
        dividerItemDecoration.setDrawable(
                ContextCompat.getDrawable(requireContext(), R.drawable.list_divider));
        recyclerView.addItemDecoration(dividerItemDecoration);
        
        // 设置RecyclerView属性
        recyclerView.setClipToPadding(false);
        
        // 等待视图完全绘制后再设置底部内边距
        setupRecyclerViewPadding();
        
        // Initialize data
        messageList = new ArrayList<>();
        
        // Set up adapter
        adapter = new MessageAdapter(getContext(), messageList);
        recyclerView.setAdapter(adapter);
        
        // Set click listener
        adapter.setOnItemClickListener(message -> {
            // Navigate to chat detail screen
            Intent intent = new Intent(getActivity(), ChatDetailActivity.class);
            intent.putExtra("chat_id", message.getId());
            intent.putExtra("chat_name", message.getName());
            startActivity(intent);
        });
        
        // Load data
        loadMessages();
        
        return root;
    }

    private void setupRecyclerViewPadding() {
        // 等待视图完全绘制后再设置底部内边距
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 移除监听器，避免重复调用
                recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                
                // 获取底部导航栏高度
                BottomNavigationView navView = requireActivity().findViewById(R.id.nav_view);
                int bottomNavHeight = navView.getMeasuredHeight();
                
                // 设置RecyclerView的底部内边距，确保最后一项不被底部导航栏遮挡
                if (bottomNavHeight > 0) {
                    recyclerView.setPadding(
                            recyclerView.getPaddingLeft(),
                            recyclerView.getPaddingTop(),
                            recyclerView.getPaddingRight(),
                            bottomNavHeight + 8); // 添加额外的8dp作为间距
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在Fragment恢复时重新设置内边距，确保在返回时也能正确显示
        setupRecyclerViewPadding();
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
    
    private int getNavigationBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void loadMessages() {
        // Show loading state
        progressBar.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        tvEmptyState.setVisibility(View.GONE);
        
        // In a real app, you would load data from a database or API
        // For now, we'll use static data
        messageList.clear();
        messageList.addAll(getStaticMessages());
        
        // Hide loading state
        progressBar.setVisibility(View.GONE);
        
        if (messageList.isEmpty()) {
            // Show empty state
            tvEmptyState.setVisibility(View.VISIBLE);
        } else {
            // Show data
            recyclerView.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
        }
    }
    
    private List<Message> getStaticMessages() {
        List<Message> messages = new ArrayList<>();
        
        // Add some static messages
        messages.add(new Message("1", "张三", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "你好，最近怎么样？", "上午10:30", 2));
        messages.add(new Message("2", "李四", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "明天一起去看电影吗？", "昨天", 0));
        messages.add(new Message("3", "王五", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "项目进展如何？", "星期二", 5));
        messages.add(new Message("4", "赵六", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "[图片]", "星期一", 0));
        messages.add(new Message("5", "产品部群聊", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "王五：下周一开会讨论新功能", "3月15日", 12));
        messages.add(new Message("6", "技术部群聊", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "李四：代码已提交，请查看", "3月10日", 0));
        messages.add(new Message("7", "小红", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "晚上有空吗？", "2月28日", 1));
        messages.add(new Message("8", "小明", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "谢谢你的帮助！", "2月26日", 0));
        messages.add(new Message("9", "小李", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "周末有安排吗？", "2月20日", 0));
        messages.add(new Message("10", "小王", "http://8.137.20.68/typro%E5%9B%BE%E5%BA%8A/xxxx.png", "资料已发送，请查收", "2月15日", 0));
        
        return messages;
    }
} 